<?php

namespace Drupal\shusy_sweepstake\Entity;

use Drupal\shusy_card\Entity\ShusyCard;
use Drupal\shusy_point_product\Entity\ShusyPointProduct;
use Drupal\shusy_sweepstake\ViewsController\Traits\ShusySweepstakeItemStatusTrait;
use Drupal\shusy_sweepstake\ViewsController\Traits\ShusySweepstakeItemTypeTrait;
use Entity;

class ShusySweepstakeItem extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $sweepstake_id = 0;

  public $name;

  public $number = 0;

  public $image = 0;

  public $type = 0;

  public $point = 0;

  public $point_product_id = 0;

  public $card_id;

  public $weight = 0;

  public $status = 0;

  use ShusySweepstakeItemStatusTrait, ShusySweepstakeItemTypeTrait;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_sweepstake_item');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }

    if (!empty($this->image)) {
      $dir = "public://shusy_banner_item/image/" . format_date(REQUEST_TIME, 'custom', 'Y/m/d');
      $result = file_prepare_directory($dir);
      if (empty($result)) {
        drupal_mkdir($dir, 0777, TRUE);
      }
      $file = file_load($this->image);
      if (!empty($file)) {
        $file->status = 1;
        file_save($file);
        $fid = $this->image;
        $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
        $file = file_move($file, "{$dir}/{$fid}.{$ext}");
        file_usage_add($file, 'shusy_banner_item', 'image', $file->fid);
      }
    }

    return parent::save();
  }

  function getPointProductOptions() {
    $options = [];
    $es = shusy_point_product_load_multiple(FALSE, [], TRUE);
    foreach ($es as $e) {
      if ($e instanceof ShusyPointProduct) {
        $options[$e->id] = t("@name @status", [
          '@name' => $e->name,
          '@status' => $e->getStatusOptions()[$e->status],
        ]);
      }
    }
    return $options;
  }

  function getCardOptions() {
    $options = [];
    $es = shusy_card_load_multiple(FALSE, [], TRUE);
    foreach ($es as $e) {
      if ($e instanceof ShusyCard) {
        $options[$e->id] = t("@name", [
          '@name' => $e->name,
        ]);
      }
    }
    return $options;
  }
}
